package ccengine

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/ccengine"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type CCEngineService struct {
	service.Service
}

// CreateDomain 创建域名
func (e *CCEngineService) CreateDomain(d *dto.DomainReq) (*dto.DomainRes, error) {

	client.Transport = &http.Transport{}
	res := &dto.DomainRes{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain"
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("CreateDomain:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["name"] = d.Name
	data["domain"] = d.Domain
	data["serviceType"] = d.ServiceType
	data["area"] = d.Area
	data["forceRedirect"] = d.ForceRedirect
	data["quic"] = d.Quic
	data["https"] = d.Https
	data["origin"] = d.Origin
	data["cache"] = d.Cache
	data["cacheKey"] = d.CacheKey
	data["advanced"] = d.Advance
	data["refererFilter"] = d.RefererFilter
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("CreateDomain:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	return res, nil
}

// UpdateDomain 更新域名
func (e *CCEngineService) UpdateDomain(d *dto.DomainReq) (*dto.DomainReq, error) {

	client.Transport = &http.Transport{}
	res := &dto.DomainReq{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id
	e.Log.Trace("UpdateDomain:", urlString)
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("UpdateDomain:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["name"] = d.Name
	data["domain"] = d.Domain
	data["serviceType"] = d.ServiceType
	data["area"] = d.Area
	data["forceRedirect"] = d.ForceRedirect
	data["quic"] = d.Quic
	data["https"] = d.Https
	data["origin"] = d.Origin
	data["cache"] = d.Cache
	data["cacheKey"] = d.CacheKey
	data["advanced"] = d.Advance
	data["refererFilter"] = d.RefererFilter
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("PUT", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("UpdateDomain:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	return res, nil
}

// StartDomain 启用加速域名
func (e *CCEngineService) StartDomain(d *dto.DomainReq) error {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id + "/start"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StartDomain:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("PUT", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("CreateStreamHub:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

// StopDomain 停用加速域名
func (e *CCEngineService) StopDomain(d *dto.DomainReq) error {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id + "/stop"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopDomain:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("PUT", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopDomain:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

// DeleteDomain 停用加速域名
func (e *CCEngineService) DeleteDomain(d *dto.DomainReq) error {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("DeleteDomain:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("DELETE", urlPath, nil)
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("CreateStreamHub:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

// SetCertificate 设置证书
func (e *CCEngineService) SetCertificate(d *dto.CertificateReq) error {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/tenants/cert"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("SetCertificate:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["ssl_certification"] = d.SslCertification
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("SetCertificate:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

// PreHotUrl 刷新预热
func (e *CCEngineService) PreHotUrl(d *dto.PreHotUrlReq) (string, error) {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id + "/preCache"
	Url, err := url.Parse(urlString)
	if err != nil {
		return "", err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("PreHotUrl:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["paths"] = d.Paths
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return "", err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return "", err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return "", err
	}
	e.Log.Trace("PreHotUrl:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return "", errors.New(result.Get("message").String())
	}

	return result.Get("data").Get("task_id").String(), nil
}

// RefreshCache 刷新缓存
func (e *CCEngineService) RefreshCache(d *dto.PreHotUrlReq) (string, error) {

	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/" + d.Id + "/refreshCache"
	Url, err := url.Parse(urlString)
	if err != nil {
		return "", err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("RefreshCache:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["paths"] = d.Paths
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return "", err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return "", err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return "", err
	}
	e.Log.Trace("RefreshCache:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return "", errors.New(result.Get("message").String())
	}
	return result.Get("data").Get("task_id").String(), nil
}

// DomainOwnerVerify 域名校验
func (e *CCEngineService) DomainOwnerVerify(d *dto.VerifyReq) (*dto.VerifyRes, error) {

	client.Transport = &http.Transport{}
	params := url.Values{}
	res := &dto.VerifyRes{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domainOwnerVerify"
	Url, err := url.Parse(urlString)
	if err != nil {
		return res, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("DomainOwnerVerify:", urlString)

	// 参数
	data := make(map[string]interface{})
	data["domain"] = d.Domain
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("DomainOwnerVerify:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}

	return res, nil
}

// DomainOwnerVerify2 域名校验
func (e *CCEngineService) DomainOwnerVerify2(d *dto.VerifyReq2) (*dto.VerifyRes, error) {
	client.Transport = &http.Transport{}
	params := url.Values{}
	res := &dto.VerifyRes{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domainOwnerVerifyBy2"
	Url, err := url.Parse(urlString)
	if err != nil {
		return res, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("DomainOwnerVerify2:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["id"] = d.TaskId
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("DomainOwnerVerify2:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("DomainOwnerVerify2:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}

	return res, nil
}

// CheckPem 校验证书
func (e *CCEngineService) CheckPem(d *dto.CheckPemReq) (*dto.CheckPemRes, error) {

	client.Transport = &http.Transport{}
	res := &dto.CheckPemRes{}
	urlPath := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/tenants/checkPem"
	// 参数
	data := make(map[string]interface{})
	data["pem"] = d.Pem
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return nil, err
	}
	e.Log.Trace("CheckPem:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return nil, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	return res, nil
}

// OriginUrlRewrite 回源url重写
func (e *CCEngineService) OriginUrlRewrite(d *dto.SaveUrlRewriteReq) error {
	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/originUrlRewrite/"

	urlString = urlString + d.DomainTaskId
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("OriginUrlRewrite:", urlString)
	// 参数
	data := make([]map[string]interface{}, 0, 3)
	for _, rewrite := range d.UrlRewrites {
		dataMap := make(map[string]interface{})
		dataMap["exactly_match"] = rewrite.ExactlyMatch
		dataMap["origin"] = rewrite.Origin
		dataMap["dest"] = rewrite.Dest
		dataMap["type"] = rewrite.Type
		data = append(data, dataMap)
	}

	bytesData, _ := json.Marshal(data)
	e.Log.Trace("OriginUrlRewrite:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("OriginUrlRewrite:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	return nil
}

// RequestUrlRewrite 访问url重写
func (e *CCEngineService) RequestUrlRewrite(d *dto.SaveUrlRewriteReq) error {
	client.Transport = &http.Transport{}
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/requestUrlRewrite/"
	urlString = urlString + d.DomainTaskId
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("OriginUrlRewrite:", urlString)
	// 参数
	data := make([]map[string]interface{}, 0, 3)
	for _, rewrite := range d.UrlRewrites {
		dataMap := make(map[string]interface{})
		dataMap["exactly_match"] = rewrite.ExactlyMatch
		dataMap["origin"] = rewrite.Origin
		dataMap["dest"] = rewrite.Dest
		dataMap["type"] = rewrite.Type
		data = append(data, dataMap)
	}
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("RequestUrlRewrite:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("RequestUrlRewrite:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// GetOriginUrlRewrite 查询回源URL重写
func (e *CCEngineService) GetOriginUrlRewrite(d *dto.GetUrlRewriteReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/originUrlRewrite/"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	urlString = urlString + d.DomainTaskId
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("GetOriginUrlRewrite:", urlString)
	// 参数
	data := make([]map[string]interface{}, 0, 3)
	for _, rewrite := range d.UrlRewrites {
		dataMap := make(map[string]interface{})
		dataMap["exactly_match"] = rewrite.ExactlyMatch
		dataMap["origin"] = rewrite.Origin
		dataMap["dest"] = rewrite.Dest
		data = append(data, dataMap)
	}
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("GetOriginUrlRewrite:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("GET", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("GetOriginUrlRewrite:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// GetRequestUrlRewrite 查询请求URL重写
func (e *CCEngineService) GetRequestUrlRewrite(d *dto.GetUrlRewriteReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/requestUrlRewrite/"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	urlString = urlString + d.DomainTaskId
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("GetRequestUrlRewrite:", urlString)
	// 参数
	data := make([]map[string]interface{}, 0, 3)
	for _, rewrite := range d.UrlRewrites {
		dataMap := make(map[string]interface{})
		dataMap["exactly_match"] = rewrite.ExactlyMatch
		dataMap["origin"] = rewrite.Origin
		dataMap["dest"] = rewrite.Dest
		data = append(data, dataMap)
	}
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("GetRequestUrlRewrite:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("GET", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("GetRequestUrlRewrite:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *CCEngineService) GetIpInfo(d *dto.GetIpInfoReq) (dto.CdnIps, error) {
	params := url.Values{}
	ips := dto.CdnIps{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/ip-info"
	Url, err := url.Parse(urlString)
	if err != nil {
		return ips, err
	}
	params.Set("tenantId", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	e.Log.Trace("GetIpInfo:", urlPath)
	// 参数
	data := make(map[string]interface{})
	data["ips"] = d.Ips
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("GetIpInfo:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return ips, err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return ips, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return ips, err
	}
	e.Log.Trace("GetIpInfo:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return ips, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &ips)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return ips, err
	}
	return ips, nil
}

func (e *CCEngineService) RefreshPreheat(d *dto.RefreshPreheatReq) (*[]dto.RefreshPreheatRes, error) {
	client.Transport = &http.Transport{}
	//params := url.Values{}
	res := make([]dto.RefreshPreheatRes, 0, 5)
	urlPath := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/ccengine/domain/refreshPreheat/detail"
	//Url, err := url.Parse(urlString)
	//if err != nil {
	//	return res, err
	//}
	//params.Set("tenantId", d.TenantId)
	//Url.RawQuery = params.Encode()
	//urlPath := Url.String()

	e.Log.Trace("RefreshPreheat:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["task_id"] = d.TaskId
	bytesData, _ := json.Marshal(data)
	e.Log.Trace("RefreshPreheat:", string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return &res, err
	}

	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return &res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return &res, err
	}
	e.Log.Trace("RefreshPreheat:", string(body))
	result := gjson.Parse(string(body))

	if result.Get("code").Int() != http.StatusOK {
		return &res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return &res, err
	}

	return &res, nil
}
